package com.wdh.kjs.fragment;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.wdh.kjs.Adapter.ListViewForScrollView;
import com.wdh.kjs.Adapter.TuijianAdapter;
import com.wdh.kjs.MainActivity;
import com.wdh.kjs.R;
import com.wdh.kjs.activity.DongTaiDetailsActivity;
import com.wdh.kjs.activity.DongtaiActivity;
import com.wdh.kjs.activity.InvestmentDetailActivity;
import com.wdh.kjs.activity.LoginActivity;
import com.wdh.kjs.activity.MoreActivity;
import com.wdh.kjs.activity.NoticeActivity;
import com.wdh.kjs.http.Httpurl;
import com.wdh.kjs.http.response.NotifyDownload;
import com.wdh.kjs.model.JsonModel;
import com.wdh.kjs.util.ToastUtils;
import com.wdh.kjs.widget.BannerViewPager;

import org.json.JSONObject;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by codingWw on 2016/3/7.
 */
public class HomePageFragment extends Fragment implements View.OnTouchListener, View.OnClickListener {
    private String statu;
    private Button loginRegister;
    private ListViewForScrollView listView;
    private TuijianAdapter adapter;
    private List<HashMap<String, String>> datas;
    private ScrollView scrollView;
    private ImageView imageView;
    private Intent intent;
    private TextView textView;
    private TextView main_platform_notice;
    private HashMap<String, String> maps = new HashMap<String, String>();
    private TextView allProject;
    private android.support.v4.app.FragmentManager manager;
    //    private FragmentTransaction transaction;
    private InvestmentFragment Investment;
    private JsonModel jsonModel;
    private TextView homepage_text;
    private ImageView zou;
    private TextView peng;
    private BannerViewPager banner;
    private String id;
    private String plagformMessage;
            private static int page = 1;
    private static int rows = 1;
    private String partyId;
    private TextView tv_kanbudao;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_chainwinfinance, container, false);

        initView(view);



        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("logininfo", getActivity().MODE_PRIVATE);
        String m = sharedPreferences.getString("loginToken", "");
        partyId = m;
        if (!m.equals("")) {
            homepage_text.setVisibility(View.GONE);
            peng.setVisibility(View.VISIBLE);
            zou.setVisibility(View.VISIBLE);
            loginRegister.setVisibility(View.INVISIBLE);
        } else {
            loginRegister.setVisibility(View.VISIBLE);
        }
        initwidge();
        setPlatfromTextMessage();
        loadData();
        getBannerList();
        return view;
    }


    private void getBannerList() {
        HttpUtils http1 = new HttpUtils();

        http1.send(HttpRequest.HttpMethod.POST, Httpurl.URL_BANNER, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {


                Gson gson = new Gson();
                jsonModel = gson.fromJson(responseInfo.result, JsonModel.class);

                if (jsonModel.success) {


                    banner.createView(jsonModel.getResult());
                    banner.startRoll();

                } else {
                    ToastUtils.showShort(getActivity(), "轮播图片暂无！");
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Log.i("codingWw", error.toString());
            }
        });
    }

    private void loadData() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("rows", "5");
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_NOTICE_ITEM, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {


                Gson gson = new Gson();
                jsonModel = gson.fromJson(responseInfo.result, JsonModel.class);
                if (jsonModel.success) {
if (jsonModel.getItems().size()==0){
    tv_kanbudao.setVisibility(View.VISIBLE);
}else {
    tv_kanbudao.setVisibility(View.GONE);
    item();
}
                }


            }

            @Override
            public void onFailure(HttpException error, String msg) {

                ToastUtils.showShort(getActivity(), "网络异常！");
            }
        });

    }

    private void item() {
        adapter = new TuijianAdapter(getContext(), initListViewData());
        listView.setAdapter(adapter);
    }

    private void initwidge() {

        listView.setOnTouchListener(this);
//        listView.setOnItemClickListener(this);
        imageView.setOnClickListener(this);
        textView.setOnClickListener(this);
        allProject.setOnClickListener(this);
        loginRegister.setOnClickListener(this);
        main_platform_notice.setOnClickListener(this);
    }

    private List<HashMap<String, String>> initListViewData() {
        datas = new ArrayList<>();
        for (int i = 0; i < jsonModel.getItems().size(); i++) {
            DecimalFormat df = new DecimalFormat("0.00");
            BigDecimal remain = new BigDecimal(jsonModel.getItems().get(i).getTargetMoney().toString()).subtract(new BigDecimal(jsonModel.getItems().get(i).getRaiseMoney().toString())).setScale(2, RoundingMode.HALF_UP);
            BigDecimal percent = new BigDecimal(jsonModel.getItems().get(i).getRaiseMoney().toString()).divide(jsonModel.getItems().get(i).getTargetMoney(),4,RoundingMode.HALF_UP).multiply(new BigDecimal(100 + ""));
//            BigDecimal percent = new BigDecimal(jsonModel.getItems().get(i).getRaiseMoney().toString()).divide(new BigDecimal(jsonModel.getItems().get(i).getTargetMoney().toString())).multiply(new BigDecimal(100 + ""));
            BigDecimal rate1 = new BigDecimal(percent + "").multiply(new BigDecimal(100 + "")).setScale(2, RoundingMode.HALF_UP);
           // int tate2 = new BigDecimal(jsonModel.getItems().get(i).getGdAnnualizedBenefitRate() + "").multiply(new BigDecimal(100 + "")).intValue();
            BigDecimal tate2=new BigDecimal(jsonModel.getItems().get(i).getGdAnnualizedBenefitRate() + "").multiply(new BigDecimal(100 + "")).setScale(2, BigDecimal.ROUND_HALF_UP);
            String  newrate1=df.format(percent);
//    switch (jsonModel.getItems().get(i).getItemStatus()){
//        case 7:
//            statu = "抢购";
//            break;
//        case 8:
//            statu = "预热中";
//            break;
//        case 9:
//            statu = "抢购完成";
//            break;
//        default:
//            break;
//    }

            if (jsonModel.getItems().get(i).getItemStatus() == 7) {
                statu = "抢购";
            } else if (jsonModel.getItems().get(i).getItemStatus() == 8) {
                statu = "预热中";
            } else if (jsonModel.getItems().get(i).getItemStatus() == 9 && jsonModel.getItems().get(i).getGdBenefitReturnStep().contains("还款中")) {
                statu = "还款中";
            } else if (jsonModel.getItems().get(i).getItemStatus() == 9 && jsonModel.getItems().get(i).getGdBenefitReturnStep().equals("还款完成")) {
                statu = "还款完成";
            } else if (jsonModel.getItems().get(i).getItemStatus() == 9 && jsonModel.getItems().get(i).getGdBenefitReturnStep().equals("募集成功")) {
                statu = "募集成功";
            } else if (jsonModel.getItems().get(i).getItemStatus() == 10) {
                statu = "坏账";
            }

            BigDecimal bigDecimal = new BigDecimal(jsonModel.getItems().get(i).getTargetMoney() + "").setScale(2, RoundingMode.HALF_UP);
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("style", jsonModel.getItems().get(i).getItemName());
//    hashMap.put("name", "测试1号");
            hashMap.put("money", "￥" + remain + "元");
            hashMap.put("per", tate2 + "%");
            //      hashMap.put("day", jsonModel.getItems().get(i).getRaiseDays() + "天");
            hashMap.put("day", jsonModel.getItems().get(i).getInterestDays() + "天");
            hashMap.put("total", "￥" + bigDecimal + "");
            hashMap.put("item_investment_state", statu);
            hashMap.put("status", jsonModel.getItems().get(i).getGdBenefitReturnStep());
            hashMap.put("percent", newrate1 + "");
            hashMap.put("itemId", jsonModel.getItems().get(i).getItemId() + "");

            datas.add(hashMap);
        }


        return datas;

    }

    private void initView(View view) {
        tv_kanbudao = (TextView) view.findViewById(R.id.tv_kanbudao);
        banner = (BannerViewPager) view.findViewById(R.id.bvp_bannnerHome);
        listView = (ListViewForScrollView) view.findViewById(R.id.shouye_liastview);
        imageView = (ImageView) view.findViewById(R.id.homepage_image);
        scrollView = (ScrollView) view.findViewById(R.id.shouye_scrollview);
        textView = (TextView) view.findViewById(R.id.homepage_text);
        scrollView.smoothScrollTo(0, 0);
        loginRegister = (Button) view.findViewById(R.id.loginRegister);
        allProject = (TextView) view.findViewById(R.id.allProject);
        homepage_text = (TextView) view.findViewById(R.id.homepage_text);
        zou = (ImageView) view.findViewById(R.id.zou);
        peng = (TextView) view.findViewById(R.id.peng);
        main_platform_notice = (TextView) view.findViewById(R.id.main_platform_notice);
        main_platform_notice.setSelected(true);
    }

//    @Override
//    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//        maps = datas.get(position);
//        intent = new Intent(this.getActivity(), InvestmentDetailActivity.class);
//        startActivity(intent);
//    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            scrollView.requestDisallowInterceptTouchEvent(false);
            listView.requestDisallowInterceptTouchEvent(true);
        } else
            scrollView.requestDisallowInterceptTouchEvent(true);
        return false;
    }

    @Override
    public void onPause() {
        banner.stopRoll();
//        MainActivity.llTab.setBackgroundColor(getResources().getColor(R.color.white));
        super.onPause();
    }
    @Override
    public void onStop() {
        super.onStop();
//        MainActivity.llTab.setBackgroundColor(getResources().getColor(R.color.white));
    }


    @Override
    public void onResume() {
        super.onResume();
        banner.startRoll();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.homepage_image:
                intent = new Intent(getActivity(), MoreActivity.class);
                startActivity(intent);
                break;
            case R.id.homepage_text:
                intent = new Intent(getActivity(), LoginActivity.class);
                startActivity(intent);
                break;
            case R.id.loginRegister:
                intent = new Intent(getActivity(), LoginActivity.class);
                intent.putExtra("state", "1");
                startActivity(intent);
                break;
            case R.id.allProject:
//                intent.putExtra("fragid",1);
//                intent=new Intent(getActivity(),AllProjectActivity.class);
//                startActivity(intent);
                MainActivity.mFragmentTabHost.setCurrentTab(1);
                break;
            case R.id.main_platform_notice: {
//                Intent intent = new Intent(getActivity(), DongtaiActivity.class);
//                startActivity(intent);
                 intent = new Intent(getActivity(), DongTaiDetailsActivity.class);
                intent.putExtra("userReceiveMessageId",id);
//            intent.putExtra("time2",maps.get("time"));
//            intent.setClass(this, NoticeDetailsActivity.class);
               startActivity(intent);
                break;
            }
            default: {
                break;
            }
        }
    }

    /**
     * 设置平台公告的信息
     */
    private void setPlatfromTextMessage() {
        RequestParams params = new RequestParams();
//        params.addBodyParameter("partyId", partyId);
        params.addBodyParameter("page", page + "");
        params.addBodyParameter("rows", rows + "");
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_DONGTAI_ACTIVITY, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Gson gson = new Gson();
                jsonModel = gson.fromJson(responseInfo.result, JsonModel.class);
                if (jsonModel.success) {
                    int totalrecords = jsonModel.getTotalrecords();
                    if (totalrecords > 0) {
                        plagformMessage = jsonModel.getPlatformTrendsList().get(0).getTitle();
                        id = jsonModel.getPlatformTrendsList().get(0).getPlatformTrendsId();
                        main_platform_notice.setText(plagformMessage);
                    }
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                ToastUtils.showShort(getActivity(), "网络异常！");
            }
        });

    }

}
